import * as XLSX from 'xlsx'

export function exportToExcel(data: Array<any>, headers: Array<string>, fileName: string) {
  let newData = JSON.parse(JSON.stringify(data))
  newData.forEach((item:any) => {
    let keys=item.keys()
    keys.forEach((key:string) => {
      if (typeof(item[key]) != 'string') {
        item[key] = JSON.stringify(item[key])
      }
    })
  })
  const wsData = [headers, ...newData]
  const ws = XLSX.utils.aoa_to_sheet(wsData)

  let h_len = headers.length
  ws['!cols'] = new Array(h_len).fill({ width: 20 })

  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbout], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)

  const a = document.createElement('a')
  a.href = url
  a.download = `${fileName}.xlsx`
  a.click()
  URL.revokeObjectURL(url)
}